package org.acegisecurity.util.expressioninterpreter;

/**
 * Abstract implementation of the Operator interface which contains some methods used by all
 * operator implementations.
 *
 * @author Jamie Craane
 * @author Ivo Woltring
 */
public abstract class AbstractOperator implements Operator {

    private static final String FALSE = "false";

    /**
     * @see Operator#apply(String[], Stack)
     */
    abstract public boolean apply(String[] roles, Stack valueStack);

    /**
     * Checks if the principal has the required role.
     *
     * @param roles        The roles the principal has.
     * @param requiredRole The role required to access the resource.
     * @return true if the principal has the given requiredRole, false otherwise
     */
    protected static boolean hasRole(String[] roles, String requiredRole) {
        if (Boolean.valueOf(requiredRole).booleanValue()) {
            return true;
        }
        if (FALSE.equals(requiredRole)) {
            return false;
        }
        for (int i = 0; i < roles.length; i++) {
            if (roles[i].equals(requiredRole)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Pushes the result of an operator to the value {@link org.acegisecurity.util.expressioninterpreter.Stack}.
     *
     * @param accessGranted The value that is pushed to the value {@link org.acegisecurity.util.expressioninterpreter.Stack}.
     * @param valueStack    The value {@link org.acegisecurity.util.expressioninterpreter.Stack} to which the value is pushed.
     */
    protected void pushResultToValueStack(boolean accessGranted, Stack valueStack) {
        valueStack.push(Boolean.toString(accessGranted));
    }
}
